{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 层级索引（hierarchical indexing）（在机器学习，深度学习不重要）",
   "id": "64e6655b734d0c05"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:47:37.443925Z",
     "start_time": "2025-01-13T14:47:37.099400Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "\n",
    "#MultiIndex是层级索引，索引类型的一种\n",
    "index1 = pd.MultiIndex.from_arrays([['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],\n",
    "                [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]], names=['cloth', 'size']) #层级索引的索引值，有两个层级，cloth和size\n",
    "\n",
    "ser_obj = pd.Series(np.random.randn(12),index=index1)\n",
    "print(ser_obj)\n",
    "print(type(ser_obj)) #Series\n",
    "print(type(ser_obj.index)) #索引类型，MultiIndex\n",
    "print(ser_obj.index) \n",
    "print(ser_obj.index.levels) #层级索引的索引值\n",
    "ser_obj.index.codes  #没那么重要，代表索引的位置"
   ],
   "id": "9e2cf32fa5f8b1d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth  size\n",
      "a      0      -1.054002\n",
      "       1      -0.103297\n",
      "       2       0.785105\n",
      "b      0      -0.905336\n",
      "       1       0.030571\n",
      "       2       0.265068\n",
      "c      0       0.809604\n",
      "       1      -0.244634\n",
      "       2      -0.303949\n",
      "d      0      -0.841495\n",
      "       1       0.189656\n",
      "       2      -0.504827\n",
      "dtype: float64\n",
      "<class 'pandas.core.series.Series'>\n",
      "<class 'pandas.core.indexes.multi.MultiIndex'>\n",
      "MultiIndex([('a', 0),\n",
      "            ('a', 1),\n",
      "            ('a', 2),\n",
      "            ('b', 0),\n",
      "            ('b', 1),\n",
      "            ('b', 2),\n",
      "            ('c', 0),\n",
      "            ('c', 1),\n",
      "            ('c', 2),\n",
      "            ('d', 0),\n",
      "            ('d', 1),\n",
      "            ('d', 2)],\n",
      "           names=['cloth', 'size'])\n",
      "[['a', 'b', 'c', 'd'], [0, 1, 2]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "FrozenList([[0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:52:10.325352Z",
     "start_time": "2025-01-13T14:52:10.316106Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#层级索引如何取数据\n",
    "print('-'*50)\n",
    "print(ser_obj['c']) #取出c的所有数据，取出的是series\n",
    "print('-'*50)\n",
    "print(ser_obj.loc['a', 2])\n",
    "print('-'*50)\n",
    "print(ser_obj[:, 2]) #取出所有行的内层索引为2的数据"
   ],
   "id": "fdba5e918647b02d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "--------------------------------------------------\n",
      "size\n",
      "0    0.809604\n",
      "1   -0.244634\n",
      "2   -0.303949\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "0.785105352042008\n",
      "--------------------------------------------------\n",
      "cloth\n",
      "a    0.785105\n",
      "b    0.265068\n",
      "c   -0.303949\n",
      "d   -0.504827\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "## 交换层级",
   "id": "92c3c3dbeebac735"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:53:03.648807Z",
     "start_time": "2025-01-13T14:53:03.640569Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(ser_obj.swaplevel())\n",
    "print('-'*50)\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "ser_obj=ser_obj.swaplevel()\n",
    "print(ser_obj)"
   ],
   "id": "4deb1374a2226f5f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -1.054002\n",
      "1     a       -0.103297\n",
      "2     a        0.785105\n",
      "0     b       -0.905336\n",
      "1     b        0.030571\n",
      "2     b        0.265068\n",
      "0     c        0.809604\n",
      "1     c       -0.244634\n",
      "2     c       -0.303949\n",
      "0     d       -0.841495\n",
      "1     d        0.189656\n",
      "2     d       -0.504827\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "cloth  size\n",
      "a      0      -1.054002\n",
      "       1      -0.103297\n",
      "       2       0.785105\n",
      "b      0      -0.905336\n",
      "       1       0.030571\n",
      "       2       0.265068\n",
      "c      0       0.809604\n",
      "       1      -0.244634\n",
      "       2      -0.303949\n",
      "d      0      -0.841495\n",
      "       1       0.189656\n",
      "       2      -0.504827\n",
      "dtype: float64\n",
      "--------------------------------------------------\n",
      "size  cloth\n",
      "0     a       -1.054002\n",
      "1     a       -0.103297\n",
      "2     a        0.785105\n",
      "0     b       -0.905336\n",
      "1     b        0.030571\n",
      "2     b        0.265068\n",
      "0     c        0.809604\n",
      "1     c       -0.244634\n",
      "2     c       -0.303949\n",
      "0     d       -0.841495\n",
      "1     d        0.189656\n",
      "2     d       -0.504827\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:53:58.494781Z",
     "start_time": "2025-01-13T14:53:58.488994Z"
    }
   },
   "cell_type": "code",
   "source": "print(ser_obj.sort_index(level=0))  #层级索引按那个索引级别排序,level=0表示按最外层索引排序，即最靠近数据的索引",
   "id": "9332303012e0d2b5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size  cloth\n",
      "0     a       -1.054002\n",
      "      b       -0.905336\n",
      "      c        0.809604\n",
      "      d       -0.841495\n",
      "1     a       -0.103297\n",
      "      b        0.030571\n",
      "      c       -0.244634\n",
      "      d        0.189656\n",
      "2     a        0.785105\n",
      "      b        0.265068\n",
      "      c       -0.303949\n",
      "      d       -0.504827\n",
      "dtype: float64\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:55:33.320756Z",
     "start_time": "2025-01-13T14:55:33.310119Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#把最大索引变为列索引\n",
    "df_obj=ser_obj.unstack()  #unstack的level参数是索引层级\n",
    "print(df_obj)"
   ],
   "id": "3725fcffa1920e0b",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -1.054002 -0.905336  0.809604 -0.841495\n",
      "1     -0.103297  0.030571 -0.244634  0.189656\n",
      "2      0.785105  0.265068 -0.303949 -0.504827\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-01-13T14:57:22.895859Z",
     "start_time": "2025-01-13T14:57:22.887218Z"
    }
   },
   "cell_type": "code",
   "source": [
    "print(df_obj)\n",
    "#对df进行stack，就会把行，列索引进行堆叠，变为series\n",
    "#把列索引放入内层,只能放到内层\n",
    "print(df_obj.stack())  #stack变为series和unstack保持一致的\n",
    "# df_obj=df_obj.transpose()\n",
    "# print(df_obj)"
   ],
   "id": "a076d03f51b29998",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "size          0         1         2\n",
      "cloth                              \n",
      "a     -1.054002 -0.103297  0.785105\n",
      "b     -0.905336  0.030571  0.265068\n",
      "c      0.809604 -0.244634 -0.303949\n",
      "d     -0.841495  0.189656 -0.504827\n",
      "cloth  size\n",
      "a      0      -1.054002\n",
      "       1      -0.103297\n",
      "       2       0.785105\n",
      "b      0      -0.905336\n",
      "       1       0.030571\n",
      "       2       0.265068\n",
      "c      0       0.809604\n",
      "       1      -0.244634\n",
      "       2      -0.303949\n",
      "d      0      -0.841495\n",
      "       1       0.189656\n",
      "       2      -0.504827\n",
      "dtype: float64\n",
      "cloth         a         b         c         d\n",
      "size                                         \n",
      "0     -1.054002 -0.905336  0.809604 -0.841495\n",
      "1     -0.103297  0.030571 -0.244634  0.189656\n",
      "2      0.785105  0.265068 -0.303949 -0.504827\n"
     ]
    }
   ],
   "execution_count": 8
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
